import datetime
import random
import hashlib
import requests
import logging
from cars.models import MthCar
from ymiot.models import ApiLog

logger = logging.getLogger("log")

# HOST = "http://openapi.qingtingjh.com/api"
# APPID = "ym8fd4c1e76ada83a8"
# PARKKEY = "q9ej72mn"
# BUSNO = "2F4D9E707167B171"
# SECRET = "af7c6698750d4d0db3074ba4a1acdd64"
HOST = "http://openapi.ymiot.net/Api"
APPID = "ymb6a010d3320c9788"
PARKKEY = "58hvcm4f"
BUSNO = "BDE537EC9E4BBA7A"
SECRET = "cd629d639ed84dccb3a31d877f72dfd0"


# 加密方法
def signdata(data):
    signeddata = data
    datasort = sorted(data.items(), key=lambda item: item[0])
    stringA = ""
    for ds in datasort:
        stringA += ds[0] + "=" + ds[1] + "&"
    stringSignTemp = stringA + SECRET
    sign = hashlib.md5(stringSignTemp.encode(encoding="UTF-8")).hexdigest().upper()
    signeddata["sign"] = sign
    return signeddata


# 增加访客车辆
def add_visitor_car(plate, begintime, endtime):
    # 接口名称
    apiname = "增加访客车辆"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{plate}>;2.开始时间<{begintime}>;3.结束时间<{endtime}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "businessNo": BUSNO,
        "carNo": plate,
        "beginTime": begintime,
        "endTime": endtime,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inform/AddVisitorCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        print("response_json:", response_json)
        response_code = response_json["code"]
        print("response_code:", response_code)
        response_msg = response_json["msg"]
        if response_code == 1:
            response_data = response_json["data"]
            visitorNo = response_data["visitorNo"]
            data["visitorNo"] = visitorNo
            data["beginTime"] = begintime
            data["endTime"] = endtime
            msg = response_msg
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.访客NO<{visitorNo}>;4.开始时间<{begintime}>;5.结束时间<{endtime}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "新增访客车辆接口返回失败1"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("新增访客车辆接口调用失败2:", e)
        code = 502
        msg = "新增访客车辆接口调用失败2"
        apioutput = f"1.code<500>;2.msg<调用失败>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 删除访客车辆
def del_visitor_car(visitorNo, carNo):
    # 接口名称
    apiname = "删除访客车辆"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{carNo}>;2.访客车辆号码<{visitorNo}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "businessNo": BUSNO,
        "visitorNo": visitorNo,
        "carNo": carNo,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inform/DeleteVisitorCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            apioutput = f"1.code<1>;2.msg<{response_msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "删除访客接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 获取单个车辆入场记录
def get_enter_car_single(plate, startTime, endTime):
    # 接口名称
    apiname = "获取单个车辆入场记录"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{plate}>;2.开始时间<{startTime}>;3.结束时间<{endTime}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "carNo": plate,
        "startTime": startTime,
        "endTime": endTime,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inquire/GetEnterCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            response_data = response_json["data"]
            data["carLst"] = response_data
            count = len(response_data)
            data["count"] = count
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.数据数量<{count}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 获取全部车辆入场记录
def get_enter_car_list(hours, page):
    # 接口名称
    apiname = "获取全部车辆入场记录"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.小时数<{hours}>;2.页码<{page}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    startTime = (datetime.datetime.now() - datetime.timedelta(hours=hours)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    endTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.1",
        "parkKey": PARKKEY,
        "startTime": startTime,
        "endTime": endTime,
        "indexId": page,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inquire/GetEnterCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            response_data = response_json["data"]
            data["carLst"] = response_data
            count = len(response_data)
            data["count"] = count
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.车辆数量<{count}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 获取单个车辆出场记录
def get_out_car_single(plate, startTime, endTime):
    # 接口名称
    apiname = "获取单个车辆出场记录"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{plate}>;2.开始时间<{startTime}>;3.结束时间<{endTime}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "carNo": plate,
        "startTime": startTime,
        "endTime": endTime,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inquire/GetOutCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            response_data = response_json["data"]
            data["carLst"] = response_data
            count = len(response_data)
            data["count"] = count
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.数据数量<{count}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 获取全部车辆出场记录
def get_out_car_list(hours, page):
    # 接口名称
    apiname = "获取全部车辆出场记录"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.小时数<{hours}>;2.页码<{page}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    startTime = (datetime.datetime.now() - datetime.timedelta(hours=hours)).strftime(
        "%Y-%m-%d %H:%M:%S"
    )
    endTime = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.1",
        "parkKey": PARKKEY,
        "startTime": startTime,
        "endTime": endTime,
        "indexId": page,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inquire/GetOutCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            response_data = response_json["data"]
            data["carLst"] = response_data
            count = len(response_data)
            data["count"] = count
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.车辆数量<{count}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 查询车辆出场记录
def get_out_car(plate, startTime, endTime):
    # 接口名称
    apiname = "查询车辆出场记录"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{plate}>;2.开始时间<{startTime}>;3.结束时间<{endTime}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "carNo": plate,
        "startTime": startTime,
        "endTime": endTime,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inquire/GetOutCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            response_data = response_json["data"]
            outTime = response_data[0]["outTime"]
            outGateName = response_data[0]["outGateName"]
            data["outTime"] = outTime
            data["outGateName"] = outGateName
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.出场时间<{outTime}>;4.出场车道<{outGateName}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 新增月租车用户
def add_person(carTypeNo, userName, homeAddress, mobNumber):
    # 接口名称
    apiname = "新增月租车用户"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.姓名<{userName}>;2.地址<{homeAddress}>;3.手机<{mobNumber}>;4.类型<{carTypeNo}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "userName": userName,
        "carTypeNo": carTypeNo,
        "homeAddress": homeAddress,
        "mobNumber": mobNumber,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inform/AddPerson"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        print(response_json)
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            response_data = response_json["data"]
            userNo = response_data["userNo"]
            data["userNo"] = userNo
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.用户编号<{userNo}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 获取月租车信息
def search_mthcar(carNo):
    # 接口名称
    apiname = "获取月租车信息"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{carNo}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    rawdata = {}
    rawdata["appid"] = APPID
    rawdata["rand"] = request_rand
    rawdata["version"] = "v1.0"
    rawdata["parkKey"] = PARKKEY
    rawdata["carNo"] = carNo
    request_sign = signdata(rawdata)
    request_url = HOST + "/Inquire/GetMthCarInfo"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        print(response_json)
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            response_data = response_json["data"]
            data["carDet"] = response_data
            count = len(response_data)
            data["count"] = count
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.数据数量<{count}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 新增月租车
def add_mthcar(carNo, userNo):
    # 接口名称
    apiname = "新增月租车"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{carNo}>;2.用户编号<{userNo}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "carNo": carNo,
        "userNo": userNo,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inform/AddMthCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        print(response_json)
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            apioutput = f"1.code<1>;2.msg<{response_msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


def charge_mthcar(carNo, beginTime, endTime):
    # 接口名称
    apiname = "月租车充值（按时间段）"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{carNo}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    # parkKey	String	是	8	车场唯一编号	1j4rdfrp
    # carNo	String	是	20	车牌号码	粤L11112
    # mthChargeMoney	String	是		充值金额(单位：元)	100
    # beginTime	String	是		有效期开始时间	yyyy-MM-dd HH:mm:ss
    # endTime	String	是		有效期结束时间	yyyy-MM-dd HH:mm:ss
    # isUpdateBeginTime	String	否		是否修改有效期开始时间	0不修改、1修改，默认0
    # version	String	是		版本号	目前仅支持版本 v1.0
    # appid	String	是		开发者应用ID	ymd68a1559cee4ab13
    # rand	String	是		随机数	请求接口时随机产生的小数，与上次请求不能重复，否则认为是非法请求，如9.949955201
    # sign	String	是		签名字符串	详情见签名算法
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "carNo": carNo,
        "mthChargeMoney": "0",
        "beginTime": beginTime,
        "endTime": endTime,
        "isUpdateBeginTime": "1",
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inform/ChargeMonthCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        print(response_json)
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            response_data = response_json["data"]
            carNo = response_data["carNo"]
            beginTime = response_data["beginTime"]
            endTime = response_data["endTime"]
            data["carNo"] = carNo
            data["beginTime"] = beginTime
            data["endTime"] = endTime
            apioutput = f"1.code<1>;2.msg<{response_msg}>;3.carNo<{carNo}>;4.beginTime<{beginTime}>;5.endTime<{endTime}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


# 注销月租车
def fail_mthcar(carNo):
    # 接口名称
    apiname = "注销月租车"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 入参
    apiinput = f"1.车牌<{carNo}>;"
    logger.info(f"接口>>>{apiname}>>>入参>>>{apiinput}")
    code = 0
    msg = "OK"
    data = {}
    request_rand = str(random.uniform(0, 9))
    request_data = {
        "appid": APPID,
        "rand": request_rand,
        "version": "v1.0",
        "parkKey": PARKKEY,
        "carNo": carNo,
    }
    request_sign = signdata(request_data)
    request_url = HOST + "/Inform/FailMonthCar"
    try:
        response = requests.post(request_url, json=request_sign)
        response_json = response.json()
        response_code = response_json["code"]
        response_msg = response_json["msg"]
        if response_code == 1:
            msg = response_msg
            apioutput = f"1.code<1>;2.msg<{response_msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
        else:
            code = 501
            msg = "接口返回失败"
            apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
            logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
    except Exception as e:
        print("接口调用失败:", e)
        code = 502
        msg = "接口调用失败"
        apioutput = f"1.code<502>;2.msg<{msg}>;"
        logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
    apiLog = ApiLog()
    apiLog.name = apiname
    apiLog.input = apiinput
    apiLog.output = apioutput
    if code == 0:
        apiLog.result = 0
    else:
        apiLog.result = 1
    apiLog.save()
    ret = {"code": code, "msg": msg, "data": data}
    return ret


def downLoadMthCar():
    # 接口名称
    now = datetime.datetime.now()
    apiname = "月租车辆同步"
    logger.info(f"接口>>>{apiname}>>>开始调用")
    # 月租车辆获取
    for i in range(100):
        print("第" + str(i + 1) + "页")
        logger.info("第" + str(i + 1) + "页")
        page = i
        rand = str(random.uniform(0, 9))
        rawdata = {}
        rawdata["appid"] = APPID
        rawdata["rand"] = rand
        rawdata["version"] = "v1.1"
        rawdata["parkKey"] = PARKKEY
        rawdata["indexId"] = str(page)
        rawdata["size"] = "100"
        signeddata = signdata(rawdata)
        url = HOST + "/Inquire/GetMthCarInfo"
        response = requests.post(url, json=signeddata)
        response_json = response.json()
        response_code = response_json["code"]
        if response_code == 1:
            carList = response_json["data"]
            if len(carList) == 0:
                print("没了，结束了")
                break
            for car in carList:
                print("car")
                print(car)
                carNo = car["carNo"]
                try:
                    mthCar = MthCar.objects.get(carNo=carNo)
                except MthCar.DoesNotExist:
                    mthCar = MthCar()
                mthCar.carNo = car["carNo"]
                mthCar.carTypeNo = car["carTypeNo"]
                mthCar.beginTime = car["beginTime"]
                mthCar.endTime = car["endTime"]
                mthCar.iusseTime = car["iusseTime"]
                mthCar.userName = car["userName"]
                mthCar.phone = car["phone"]
                mthCar.homeAddress = car["homeAddress"]
                mthCar.save()
        else:
            continue


def updateMthCar():
    now = datetime.datetime.now()
    apiname = "丢失车辆同步"
    # 找到没了的车
    logger.info(f"接口>>>{apiname}>>>开始处理免费车辆")
    errCarLst = MthCar.objects.filter(updated__lt=now)
    for errCar in errCarLst:
        endTime = errCar.endTime
        endTime = datetime.datetime.strptime(endTime, "%Y-%m-%d %H:%M:%S")
        if endTime < datetime.datetime.now():
            print("月租车已过期")
            continue
        else:
            print("月租车未过期")
            print("开始续租")
            carNo = errCar.carNo
            print(carNo)
            info_rand = str(random.uniform(0, 9))
            info_rawdata = {}
            info_rawdata["appid"] = APPID
            info_rawdata["rand"] = info_rand
            info_rawdata["version"] = "v1.0"
            info_rawdata["parkKey"] = PARKKEY
            info_rawdata["carNo"] = carNo
            info_signeddata = signdata(info_rawdata)
            info_url = HOST + "/Inquire/GetMthCarInfo"
            try:
                info_response = requests.post(info_url, json=info_signeddata)
                info_response_json = info_response.json()
            except Exception as e:
                print("接口失败")
                print(e)
                continue
            info_response_code = info_response_json["code"]
            if info_response_code == 1:
                print("月租车存在")
                info_response_data = info_response_json["data"]
                errCar.carNo = info_response_data["carNo"]
                errCar.carTypeNo = info_response_data["carTypeNo"]
                errCar.beginTime = info_response_data["beginTime"]
                errCar.endTime = info_response_data["endTime"]
                errCar.iusseTime = info_response_data["iusseTime"]
                errCar.userName = info_response_data["userName"]
                errCar.phone = info_response_data["phone"]
                errCar.homeAddress = info_response_data["homeAddress"]
                errCar.save()
            else:
                add_response = add_mthcar(carNo, errCar.userNo)
                add_response_code = add_response["code"]
                if add_response_code == 1:
                    print("月租车新增成功")
                    charge_response = charge_mthcar(carNo, errCar.beginTime, errCar.endTime)
                    charge_response_code = charge_response["code"]
                    if charge_response_code == 0:
                        print("续费成功")
                    else:
                        print("续费失败")
                        continue
                else:
                    addP_response = add_person(errCar.carTypeNo, errCar.userName, errCar.homeAddress, errCar.phone)
                    addP_response_code = addP_response["code"]
                    if addP_response_code == 0:
                        print("新增人员成功")
                        userNo = addP_response["data"]["userNo"]
                        errCar.userNo = userNo
                        errCar.save()
                        addPC = add_mthcar(carNo,userNo)
                        addPC_code = addPC["code"]
                        if addPC_code != 0:
                            print("新增月租车失败")
                        else:
                            addPCC = charge_mthcar(carNo, errCar.beginTime, errCar.endTime)
                            addPCC_code = addPCC["code"]
                            if addPCC_code == 0:
                                print("续费成功")
                            else:
                                print("续费失败")
                    else:
                        print("新增人员失败")








# 查询停车场剩余车位

# request_rand = str(random.uniform(0, 9))
# request_data = {
#     "appid": APPID,
#     "rand": request_rand,
#     "version": "v1.0",
#     "parkKey": PARKKEY,
# }
# request_sign = signdata(request_data)
# request_url = HOST + "/Inquire/GetRemainingSpace"
# try:
#     response = requests.post(request_url, json=request_sign)
#     response_json = response.json()
#     response_code = response_json["code"]
#     response_msg = response_json["msg"]
#     if response_code == 1:
#         msg = response_msg
#         response_data = response_json["data"]
#         data["carLst"] = response_data
#         count = len(response_data)
#         data["count"] = count
#         apioutput = f"1.code<1>;2.msg<{response_msg}>;3.数据数量<{count}>;"
#         logger.info(f"接口>>>{apiname}>>>执行成功>>>{apioutput}")
#     else:
#         code = 501
#         msg = "接口返回失败"
#         apioutput = f"1.code<{response_code}>;2.msg<{msg}>;"
#         logger.info(f"接口>>>{apiname}>>>执行失败>>>{apioutput}")
# except Exception as e:
#     print("接口调用失败:", e)
#     code = 502
#     msg = "接口调用失败"
#     apioutput = f"1.code<502>;2.msg<{msg}>;"
#     logger.info(f"接口>>>{apiname}>>>调用失败>>>{apioutput}")
# apiLog = ApiLog()
# apiLog.name = apiname
# apiLog.input = apiinput
# apiLog.output = apioutput
# if code == 0:
#     apiLog.result = 0
# else:
#     apiLog.result = 1
# apiLog.save()
# ret = {"code": code, "msg": msg, "data": data}
# return ret

